package com.example.lettcode._20241011;

import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/*
290. 单词规律
给定一种规律 pattern 和一个字符串 s ，判断 s 是否遵循相同的规律。
这里的 遵循 指完全匹配，例如， pattern 里的每个字母和字符串 s 中的每个非空单词之间存在着双向连接的对应规律。

示例1:
输入: pattern = "abba", s = "dog cat cat dog"
输出: true

示例 2:
输入:pattern = "abba", s = "dog cat cat fish"
输出: false

示例 3:
输入: pattern = "aaaa", s = "dog cat cat dog"
输出: false
 */
public class Dan_ci_gui_lv {

    public static void main(String[] args) {
        String pattern = "abba";
        String s = "dog cat cat dog";

        // String pattern = "aaaa";
        // String s = "dog cat cat dog";
        System.out.println(wordPattern(pattern, s));
    }


    public static boolean wordPattern(String pattern, String s) {
        int m = pattern.length();
        String[] split = s.split("\\s+");
        int n = split.length;
        if (m != n) {
            return false;
        }

        Map<Character, String> map1 = new HashMap<>();
        Map<String, Character> map2 = new HashMap<>();

        for (int i = 0; i < m; i++) {
            char c = pattern.charAt(i);
            String s1 = split[i];
            if (map1.containsKey(c) && !map1.get(c).equals(s1) || !map1.containsKey(c) && map2.containsKey(s1)) {
                return false;
            }
            map1.put(c, s1);
            map2.put(s1, c);
        }
        return true;
    }

    public static boolean wordPattern2(String pattern, String s) {
        int m = pattern.length();
        List list = Arrays.asList(s.split("\\s+"));
        int n = list.size();
        if (m != n) {
            return false;
        }

        for (int i = 0; i < m; i++) {
            int index1 = pattern.indexOf(pattern.charAt(i));
            int index2 = list.indexOf(list.get(i));
            if (index1 != index2) {
                return false;
            }
        }
        return true;
    }
}
